package mqtt

import (
	"fmt"
	"github.com/eclipse/paho.mqtt.golang"
	"log"
	"mqtt_on_offline/webscoket"
	"time"
)

var MessageSubHandler mqtt.MessageHandler = func(client mqtt.Client, message mqtt.Message){
	currentTime:=time.Now()
	fmt.Println("currentTime :  \n", currentTime)
	fmt.Println("Sub Client Topic : \n", message.Topic())
	fmt.Println("Sub Client online or offline  msg : \n", string(message.Payload()))
	// TODO  将客户端的上下线信息，通过WebSocket传输给前端页面信息
	webscoket.Conn.WriteMessage([]byte(fmt.Sprint(message.Topic())))
	err :=  webscoket.Conn.WriteMessage([]byte(string(message.Payload())))
	if err != nil{
		return
	}
	// TODO  将客户端的上下线信息，保存到Redis中，提供查询操作
}

/***
*
* 连接任务和消息订阅方法
 */

func MqttConnSubMsgTask()  {
	opts := mqtt.NewClientOptions().AddBroker("tcp://10.10.1.49:1883").SetUsername("admin").SetPassword("123456")
	opts.SetProtocolVersion(4)
	clientId := fmt.Sprintf("goSubscribe_%d",  time.Now().Unix())
	println("The SubClient Id is : ", clientId)
	opts.SetClientID(clientId)

	c := mqtt.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	//发布消息
	token := c.Subscribe("$SYS/brokers/+/clients/+/+", 1, MessageSubHandler)
	log.Print("start Mqtt client ...")
	token.Wait()
	fmt.Println("mqtt client server is OK")
}